import os
import shutil
import stat

from config.logger_config import init_logger

logger = init_logger()


def format_size(size_bytes):
    """
    将字节数格式化为人类可读的字符串
    """
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size_bytes < 1024.0:
            break
        size_bytes /= 1024.0
    return f"{size_bytes:.2f} {unit}"


def get_size(scan_path):
    if os.path.exists(scan_path):
        if os.path.isfile(scan_path):
            return os.stat(scan_path).st_size
        elif os.path.isdir(scan_path):
            total_size = 0
            for root, dirs, files in os.walk(scan_path):
                for file in files:
                    file_size = os.stat(f'{root}/{file}').st_size
                    total_size += file_size
            return total_size
        else:
            logger.info(f'path {scan_path} is unknown type')
            return None
    else:
        logger.info(f'path {scan_path} is not exists, cannot calc size')
        return None


def is_folder_empty(scan_path):
    return os.path.exists(scan_path) and os.path.isdir(scan_path) and not os.listdir(scan_path)


def clear_path(scan_path):
    """
       if scan_path is file, then remove it. if scan_path is folder, then try to clean this folder
       if the folder contains the file that in use, this function will remove the other unused files
       this function will not remove the folder itself
       :param scan_path:
       :return: freed space in byte
       """
    total_freed = 0
    if os.path.exists(scan_path):
        if os.path.isfile(scan_path):
            try:
                occupied = get_size(scan_path)
                os.remove(scan_path)
                total_freed += occupied
            except:
                pass
        elif os.path.isdir(scan_path):
            for root, dirs, files in os.walk(scan_path):
                for file in files:
                    try:
                        file_path = f'{root}/{file}'
                        occupied = get_size(file_path)
                        if os.path.isfile(file_path):
                            os.remove(file_path)
                        else:
                            shutil.rmtree(file_path)
                        total_freed += occupied
                    except:
                        pass
    return total_freed


if __name__ == "__main__":
    pass
